import { ParserRuleContext } from 'antlr4ts';
import { TerminalNode } from 'antlr4ts/tree/TerminalNode';
import { ArkcubeScriptListener } from '../gen/ArkcubeScriptListener';
import { Token } from 'antlr4ts/Token';
import { ParseTreeWalker } from 'antlr4ts/tree/ParseTreeWalker';

import {
	Location,
	Position
} from 'vscode-languageserver/node';
import { ParseTree } from 'antlr4ts/tree/ParseTree';

export class PositionAwareListener implements ArkcubeScriptListener {

	private position: Position;
	public foundNode: ParserRuleContext | TerminalNode | null = null;

    static getPositionAst(position: Position, tree: ParseTree):ParserRuleContext | TerminalNode | null {
        const listener = new PositionAwareListener(position);
        ParseTreeWalker.DEFAULT.walk(listener, tree);
        return listener.foundNode;
    }
	constructor(position: Position) {
		this.position = position;
	}

	// 检查节点是否包含目标位置
    private isNodeAtPosition(node: ParserRuleContext | TerminalNode): boolean {
        let start: Token, stop: Token;
        
        if (node instanceof ParserRuleContext) {
            start = node.start;
            stop = node.stop || node.start;
        } else {
            start = stop = node.symbol;
        }
        
        return (
            (this.position.line + 1 > start.line || 
             (this.position.line + 1 === start.line && this.position.character >= start.charPositionInLine)) &&
            (this.position.line + 1 < stop.line || 
             (this.position.line + 1 === stop.line && this.position.character <= stop.charPositionInLine + (stop.text?.length || 0)))
        );
    }
	
	// 覆盖所有enter方法，查找最具体的节点
    enterEveryRule(ctx: ParserRuleContext) {
        if (this.isNodeAtPosition(ctx)) {
            this.foundNode = ctx;
        }
    }

	visitTerminal(node: TerminalNode) {
        if (this.isNodeAtPosition(node)) {
            this.foundNode = node;
        }
    }
	
} 
